package com.farmer.expert.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farmer.common.entity.AgriExpert;
import com.farmer.common.result.Result;
import com.farmer.expert.mapper.ExpertMapper;
import com.farmer.expert.service.ExpertService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 农业专家服务实现类
 */
@Slf4j
@Service
public class ExpertServiceImpl implements ExpertService {

    @Autowired
    private ExpertMapper expertMapper;

    @Override
    public Result<?> getExpertList(Integer pageNum, Integer pageSize, String specialties, String availableStatus, Integer isVerified, String keyword) {
        try {
            Page<AgriExpert> page = new Page<>(pageNum, pageSize);
            QueryWrapper<AgriExpert> queryWrapper = new QueryWrapper<>();

            // 专业领域过滤
            if (StringUtils.hasText(specialties)) {
                queryWrapper.like("specialties", specialties);
            }

            // 可用状态过滤
            if (StringUtils.hasText(availableStatus)) {
                queryWrapper.eq("available_status", availableStatus);
            }

            // 认证状态过滤
            if (isVerified != null) {
                queryWrapper.eq("is_verified", isVerified);
            }

            // 关键词搜索（姓名、职称、机构）
            if (StringUtils.hasText(keyword)) {
                queryWrapper.and(wrapper -> wrapper
                    .like("name", keyword)
                    .or()
                    .like("title", keyword)
                    .or()
                    .like("organization", keyword)
                );
            }

            // 按评分和创建时间排序
            queryWrapper.orderByDesc("rating", "create_time");

            Page<AgriExpert> expertPage = expertMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", expertPage.getRecords());
            result.put("total", expertPage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取专家列表成功", result);
        } catch (Exception e) {
            log.error("获取专家列表失败：{}", e.getMessage(), e);
            return Result.error("获取专家列表失败");
        }
    }

    @Override
    public Result<?> getExpertById(Long expertId) {
        try {
            if (expertId == null) {
                return Result.error("专家ID不能为空");
            }

            AgriExpert expert = expertMapper.selectById(expertId);
            if (expert == null) {
                return Result.error("专家不存在");
            }

            return Result.success("获取专家详情成功", expert);
        } catch (Exception e) {
            log.error("获取专家详情失败：{}", e.getMessage(), e);
            return Result.error("获取专家详情失败");
        }
    }

    @Override
    public Result<?> addExpert(AgriExpert expert) {
        try {
            if (expert == null) {
                return Result.error("专家信息不能为空");
            }

            if (!StringUtils.hasText(expert.getName())) {
                return Result.error("专家姓名不能为空");
            }

            // 设置默认值
            // 生成专家编号
            if (!StringUtils.hasText(expert.getExpertNo())) {
                expert.setExpertNo(generateExpertNo());
            }
            // 设置机构默认值
            if (!StringUtils.hasText(expert.getOrganization())) {
                expert.setOrganization("");
            }
            // 设置性别默认值
            if (expert.getGender() == null) {
                expert.setGender(0); // 0-未知
            }
            // 设置评分默认值
            if (expert.getRating() == null) {
                expert.setRating(BigDecimal.ZERO);
            }
            // 设置咨询费用默认值
            if (expert.getConsultationFee() == null) {
                expert.setConsultationFee(BigDecimal.ZERO);
            }
            if (expert.getConsultationCount() == null) {
                expert.setConsultationCount(0);
            }
            if (expert.getCourseCount() == null) {
                expert.setCourseCount(0);
            }
            if (expert.getRatingCount() == null) {
                expert.setRatingCount(0);
            }
            if (expert.getIsVerified() == null) {
                expert.setIsVerified(0);
            }
            if (expert.getStatus() == null) {
                expert.setStatus(1);
            }
            if (expert.getAvailableStatus() == null) {
                expert.setAvailableStatus("AVAILABLE");
            }

            int result = expertMapper.insert(expert);
            if (result > 0) {
                return Result.success("添加专家成功", expert);
            } else {
                return Result.error("添加专家失败");
            }
        } catch (Exception e) {
            log.error("添加专家失败：{}", e.getMessage(), e);
            return Result.error("添加专家失败");
        }
    }

    @Override
    public Result<?> updateExpert(AgriExpert expert) {
        try {
            if (expert == null || expert.getId() == null) {
                return Result.error("专家ID不能为空");
            }

            AgriExpert existingExpert = expertMapper.selectById(expert.getId());
            if (existingExpert == null) {
                return Result.error("专家不存在");
            }

            int result = expertMapper.updateById(expert);
            if (result > 0) {
                return Result.success("更新专家信息成功");
            } else {
                return Result.error("更新专家信息失败");
            }
        } catch (Exception e) {
            log.error("更新专家信息失败：{}", e.getMessage(), e);
            return Result.error("更新专家信息失败");
        }
    }

    @Override
    public Result<?> deleteExpert(Long expertId) {
        try {
            if (expertId == null) {
                return Result.error("专家ID不能为空");
            }

            AgriExpert expert = expertMapper.selectById(expertId);
            if (expert == null) {
                return Result.error("专家不存在");
            }

            int result = expertMapper.deleteById(expertId);
            if (result > 0) {
                return Result.success("删除专家成功");
            } else {
                return Result.error("删除专家失败");
            }
        } catch (Exception e) {
            log.error("删除专家失败：{}", e.getMessage(), e);
            return Result.error("删除专家失败");
        }
    }

    @Override
    public Result<?> updateExpertStatus(Long expertId, Integer status) {
        try {
            if (expertId == null) {
                return Result.error("专家ID不能为空");
            }

            if (status == null) {
                return Result.error("状态不能为空");
            }

            AgriExpert expert = expertMapper.selectById(expertId);
            if (expert == null) {
                return Result.error("专家不存在");
            }

            expert.setStatus(status);
            int result = expertMapper.updateById(expert);
            if (result > 0) {
                return Result.success("更新专家状态成功");
            } else {
                return Result.error("更新专家状态失败");
            }
        } catch (Exception e) {
            log.error("更新专家状态失败：{}", e.getMessage(), e);
            return Result.error("更新专家状态失败");
        }
    }

    @Override
    public Result<?> updateAvailableStatus(Long expertId, String availableStatus) {
        try {
            if (expertId == null) {
                return Result.error("专家ID不能为空");
            }

            if (!StringUtils.hasText(availableStatus)) {
                return Result.error("可用状态不能为空");
            }

            AgriExpert expert = expertMapper.selectById(expertId);
            if (expert == null) {
                return Result.error("专家不存在");
            }

            expert.setAvailableStatus(availableStatus);
            int result = expertMapper.updateById(expert);
            if (result > 0) {
                return Result.success("更新专家可用状态成功");
            } else {
                return Result.error("更新专家可用状态失败");
            }
        } catch (Exception e) {
            log.error("更新专家可用状态失败：{}", e.getMessage(), e);
            return Result.error("更新专家可用状态失败");
        }
    }

    @Override
    public Result<?> verifyExpert(Long expertId, Integer isVerified) {
        try {
            if (expertId == null) {
                return Result.error("专家ID不能为空");
            }

            if (isVerified == null) {
                return Result.error("认证状态不能为空");
            }

            AgriExpert expert = expertMapper.selectById(expertId);
            if (expert == null) {
                return Result.error("专家不存在");
            }

            expert.setIsVerified(isVerified);
            int result = expertMapper.updateById(expert);
            if (result > 0) {
                return Result.success("专家认证状态更新成功");
            } else {
                return Result.error("专家认证状态更新失败");
            }
        } catch (Exception e) {
            log.error("专家认证失败：{}", e.getMessage(), e);
            return Result.error("专家认证失败");
        }
    }

    @Override
    public Result<?> getRecommendedExperts(Integer limit) {
        try {
            if (limit == null || limit <= 0) {
                limit = 10;
            }

            QueryWrapper<AgriExpert> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1)
                       .eq("is_verified", 1)
                       .eq("available_status", "AVAILABLE")
                       .orderByDesc("rating", "consultation_count")
                       .last("LIMIT " + limit);

            List<AgriExpert> expertList = expertMapper.selectList(queryWrapper);
            return Result.success("获取推荐专家成功", expertList);
        } catch (Exception e) {
            log.error("获取推荐专家失败：{}", e.getMessage(), e);
            return Result.error("获取推荐专家失败");
        }
    }

    @Override
    public Result<?> getExpertsBySpecialties(String specialties, Integer pageNum, Integer pageSize) {
        try {
            if (!StringUtils.hasText(specialties)) {
                return Result.error("专业领域不能为空");
            }

            Page<AgriExpert> page = new Page<>(pageNum, pageSize);
            QueryWrapper<AgriExpert> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("specialties", specialties)
                       .eq("status", 1)
                       .orderByDesc("rating", "consultation_count");

            Page<AgriExpert> expertPage = expertMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", expertPage.getRecords());
            result.put("total", expertPage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取专业领域专家列表成功", result);
        } catch (Exception e) {
            log.error("获取专业领域专家列表失败：{}", e.getMessage(), e);
            return Result.error("获取专业领域专家列表失败");
        }
    }

    @Override
    public Result<?> increaseConsultationCount(Long expertId) {
        try {
            if (expertId == null) {
                return Result.error("专家ID不能为空");
            }

            AgriExpert expert = expertMapper.selectById(expertId);
            if (expert == null) {
                return Result.error("专家不存在");
            }

            expert.setConsultationCount(expert.getConsultationCount() + 1);
            int result = expertMapper.updateById(expert);
            if (result > 0) {
                return Result.success("增加咨询次数成功");
            } else {
                return Result.error("增加咨询次数失败");
            }
        } catch (Exception e) {
            log.error("增加咨询次数失败：{}", e.getMessage(), e);
            return Result.error("增加咨询次数失败");
        }
    }

    @Override
    public Result<?> increaseCourseCount(Long expertId) {
        try {
            if (expertId == null) {
                return Result.error("专家ID不能为空");
            }

            AgriExpert expert = expertMapper.selectById(expertId);
            if (expert == null) {
                return Result.error("专家不存在");
            }

            expert.setCourseCount(expert.getCourseCount() + 1);
            int result = expertMapper.updateById(expert);
            if (result > 0) {
                return Result.success("增加授课次数成功");
            } else {
                return Result.error("增加授课次数失败");
            }
        } catch (Exception e) {
            log.error("增加授课次数失败：{}", e.getMessage(), e);
            return Result.error("增加授课次数失败");
        }
    }

    @Override
    public Result<?> updateRating(Long expertId, Double rating) {
        try {
            if (expertId == null) {
                return Result.error("专家ID不能为空");
            }

            if (rating == null || rating < 0 || rating > 5) {
                return Result.error("评分必须在0-5之间");
            }

            AgriExpert expert = expertMapper.selectById(expertId);
            if (expert == null) {
                return Result.error("专家不存在");
            }

            expert.setRating(BigDecimal.valueOf(rating));
            expert.setRatingCount(expert.getRatingCount() + 1);
            int result = expertMapper.updateById(expert);
            if (result > 0) {
                return Result.success("更新专家评分成功");
            } else {
                return Result.error("更新专家评分失败");
            }
        } catch (Exception e) {
            log.error("更新专家评分失败：{}", e.getMessage(), e);
            return Result.error("更新专家评分失败");
        }
    }

    @Override
    public Result<?> getExpertStatistics() {
        try {
            QueryWrapper<AgriExpert> queryWrapper = new QueryWrapper<>();
            Long totalExperts = expertMapper.selectCount(queryWrapper);

            queryWrapper.clear();
            queryWrapper.eq("status", 1);
            Long activeExperts = expertMapper.selectCount(queryWrapper);

            queryWrapper.clear();
            queryWrapper.eq("is_verified", 1);
            Long verifiedExperts = expertMapper.selectCount(queryWrapper);

            queryWrapper.clear();
            queryWrapper.eq("available_status", "AVAILABLE");
            Long availableExperts = expertMapper.selectCount(queryWrapper);

            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalExperts", totalExperts);
            statistics.put("activeExperts", activeExperts);
            statistics.put("verifiedExperts", verifiedExperts);
            statistics.put("availableExperts", availableExperts);

            return Result.success("获取专家统计信息成功", statistics);
        } catch (Exception e) {
            log.error("获取专家统计信息失败：{}", e.getMessage(), e);
            return Result.error("获取专家统计信息失败");
        }
    }

    /**
     * 生成专家编号
     * @return 专家编号，格式：EXP + 年月日 + 4位随机数
     */
    private String generateExpertNo() {
        String dateStr = LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));
        int randomNum = (int)(Math.random() * 9000) + 1000; // 生成1000-9999的随机数
        return "EXP" + dateStr + randomNum;
    }
} 